package com.jy.modules.cims.common.sysUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @description HttpClient
 * @author shengzhoutao
 * @date 2015-7-29 
 */

@SuppressWarnings("deprecation")
public class HttpUtils {

	// 创建HttpClient对象
	public static HttpClient httpClient = new DefaultHttpClient();

	/**
	 * @description getRequest
	 * @param url
	 *            发送请求的URL
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	public static String getRequest(final String url) throws Exception {

		// 创建HttpGet对象。
		HttpGet httpGet = new HttpGet(url);

		// 发送GET请求
		HttpResponse httpResponse = httpClient.execute(httpGet);

		// 如果服务器成功地返回响应
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 获取服务器响应字符串
			String result = EntityUtils.toString(httpResponse.getEntity());
			return result;
		}

		return null;

	}

	/**
	 * @description postRequest
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	public static String postRequest(final String url, final String params) throws Exception {

		// 创建HttpPost对象。
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");

		// 设置请求参数
		httpPost.setEntity(new StringEntity(params, "UTF-8"));

		// 发送POST请求
		HttpResponse httpResponse = httpClient.execute(httpPost);

		// 如果服务器成功地返回响应
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 获取服务器响应字符串
			String result = EntityUtils.toString(httpResponse.getEntity());
			return result;
		}

		return null;
	}

	/**
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	public static String postRequest(final String url, final Map<String, String> rawParams) throws Exception {

		// 创建HttpPost对象。
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");

		if (null != rawParams) {
			// 如果传递参数个数比较多的话可以对传递的参数进行封装
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for (String key : rawParams.keySet()) { // 封装请求参数
				params.add(new BasicNameValuePair(key, rawParams.get(key)));
			}
		}

		// 发送POST请求
		HttpResponse httpResponse = httpClient.execute(httpPost);

		// 如果服务器成功地返回响应
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 获取服务器响应字符串
			String result = EntityUtils.toString(httpResponse.getEntity());
			return result;
		}
		return null;
	}
}